package com.ibeetl.admin.api.web;

import com.ibeetl.admin.api.service.FileService;
import com.ibeetl.admin.core.web.JsonResult;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class FileController {
    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/api/file";
    @Resource
    private FileService fileService;
    //设置时间格式
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    @Value("${upload.path}")
    private String filePath;

    @Operation(
            summary = "文件上传",
            description = "上传文件到服务器"
    )
    @PostMapping(MODEL+"/upload")
    @CrossOrigin
    public JsonResult<String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
        if (file.isEmpty()) {
            return JsonResult.fail();
        }
        try {
            //1、处理文件位置
            //文件存放位置
            String realPath = filePath+File.separator+"userId"+File.separator+"jdID"+File.separator;
            log.info("realPath = "+realPath);
            //按照时间格式划分
            String format = sdf.format(new Date());
            String path = realPath + format;
            //文件夹
            File folder = new File(path);
            //判断文件是否存在
            if (!folder.exists()) {//不存在，则创建
                //这里需要使用mkdirs，因为为多层目录
                folder.mkdirs();
            }
            //2、处理文件名
            //获取文件后缀+文件名
            String oldName = file.getOriginalFilename();
            //将后缀加到新的文件名上
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            try {
                //文件保存
                file.transferTo(new File(folder, newName));
                //获取请求协议                            获取主机名                       获取端口
                String s = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName;//文件的访问路径
                log.debug(s);
                return JsonResult.success(path+File.separator+newName);
            } catch (IOException e) {
                return JsonResult.fail(e.getMessage());
            }

        } catch (Exception e) {
            return JsonResult.fail(e.getMessage());
        }
    }




    @PostMapping("/load2")
    @CrossOrigin
    public void upload(MultipartFile[] files, HttpServletRequest req){//参数名需要与form表单中设置的 name属性值对应上，否则获取到的为null
        //1、处理文件位置
        //文件存放位置
        String realPath = req.getServletContext().getRealPath("/");
        //按照时间格式划分
        String format = sdf.format(new Date());
        String path = realPath + format;
        //文件夹
        File folder = new File(path);
        //判断文件是否存在
        if (!folder.exists()){//不存在，则创建
            //这里需要使用mkdirs，因为为多层目录
            folder.mkdirs();
        }
        try {
            for (MultipartFile file : files) {
                //2、处理文件名
                //获取文件后缀+文件名
                String oldName = file.getOriginalFilename();
                //将后缀加到新的文件名上
                String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
                //文件保存
                file.transferTo(new File(folder, newName));
                //获取请求协议                            获取主机名                       获取端口
                String s = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName;//文件的访问路径
                System.out.println("s = " + s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @Operation(
            summary = "文件下载",
            description = "文件流下载"
    )
    @PostMapping(MODEL+"/download")
    @CrossOrigin
    public ResponseEntity<InputStreamResource> downloadFile(String filePath) throws IOException {
        return fileService.downloadFile(filePath);

    }



}
